import json
import urllib.request
import time
import hmac
import hashlib
import base64
import urllib.parse

class Newrobot:
    url = "https://oapi.dingtalk.com/robot/send"

    def __init__(self, secret, access_token):
        self.secret = secret
        self.access_token = access_token
        timestamp = str(round(time.time() * 1000))
        secret_enc = self.secret.encode('utf-8')
        string_to_sign = '{}\n{}'.format(timestamp, self.secret)
        string_to_sign_enc = string_to_sign.encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        self.sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
        self.url='https://oapi.dingtalk.com/robot/send?access_token={}&timestamp={}&sign={}'.format(self.access_token,timestamp,self.sign)
        
    def request(self,data):
        header = {
            "Content-Type": "application/json",
            "Charset": "UTF-8"
        }
        
        # 对请求的数据进行json封装
        sendData = json.dumps(data)#将字典类型数据转化为json格式
        sendData = sendData.encode("utf-8") # python3的Request要求data为byte类型

        # 发送请求
        request = urllib.request.Request(url=self.url, data=sendData, headers=header)
        
        # 将请求发回的数据构建成为文件格式
        opener = urllib.request.urlopen(request)
        # 打印返回的结果
        print(opener.read())